package com.automannn.springPractice.applicationContext;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 注释配置应用程序作为ioc容器测试
 *
 * @author chenkh
 * @time 2021/8/20 11:35
 * @date 2022/08/03
 */
@Configuration
@Import(AnnotationConfigApplicationAsIocContainerTest.Config.class)
public class AnnotationConfigApplicationAsIocContainerTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AnnotationConfigApplicationAsIocContainerTest.class);
        registerUserDefinition(context,"karry");
        registerUserDefinition(context);

        context.refresh();
        Map<String, User> userMap = context.getBeansOfType(User.class);
        Map<String, Config> configMap = context.getBeansOfType(Config.class);
        System.out.println(userMap);
        System.out.println(configMap);
        // Object user = context.getBean(User.class);
        // Object config = context.getBean(Config.class);
        context.close();
        // Object user1 = context.getBean("hk");
        // Object user2= context.getBean("hk-alias");
        // System.out.println(user.toString());
        // System.out.println(config.toString());


        // System.out.println(user1.toString());
        // System.out.println(user2.toString());
    }

    public static void registerUserDefinition(BeanDefinitionRegistry registry,String beanName){
        BeanDefinitionBuilder builder=BeanDefinitionBuilder.genericBeanDefinition(User.class);
        builder.addPropertyValue("age",22).addPropertyValue("name","karry");
        //命名bean方式
        if(StringUtils.isNotBlank(beanName)){
            registry.registerBeanDefinition(beanName,builder.getBeanDefinition());
        }else{
            //非命名方式
            BeanDefinitionReaderUtils.registerWithGeneratedName(builder.getBeanDefinition(),registry);
        }
    }

    public static void registerUserDefinition(BeanDefinitionRegistry registry){
        registerUserDefinition(registry,null);
    }

    @Component
    public static class Config{
        /**
         * 获取用户，交给spring管理，名字以方法名为准
         *
         * @return {@link User}
         */
        @Bean
        public User getUser() {
            User user = new User();
            user.setAge(30);
            user.setName("huangk");
            return user;
        }
    }




}
